package C8_11_EncapsulateCollection;

import org.junit.Assert;
import org.junit.Test;

import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * @author xufy
 * @version 1.0
 * @description 封装集合， 返回集合的只读副本
 **/
public class EncapsulateCollectionTest {


    /**
     * 重构前
     */
    @Test
    public void test1() {
        Person kent = new Person();
        Set s = new HashSet();
        s.add(new Course("Smalltalk Programming", false));
        s.add(new Course("Appreciating Single Malts", true));
        kent.setCourse(s);
        Assert.assertEquals(2, kent.getCourse().size());
        Course refact = new Course("Refactoring", true);
        kent.getCourse().add(refact);
        kent.getCourse().add(new Course("Brutal Sarcasm", false));
        Assert.assertEquals(4, kent.getCourse().size());
        kent.getCourse().remove(refact);
        Assert.assertEquals(3, kent.getCourse().size());

    }

    /**
     * 重构后
     */
    @Test
    public void test2() {
        Person2 kent = new Person2();
        kent.addCourse(new Course("Smalltalk Programming", false));
        kent.addCourse(new Course("Appreciating Single Malts", true));
    }

}
class Person {
    private Set _courses;
    public Set getCourse() {
        return _courses;
    }
    public void setCourse(Set arg) {
        _courses = arg;
    }

}
class Person2 {

    private Set _courses = new HashSet();

    //重构第三步 只读副本
    public Set getCourse() {
        return Collections.unmodifiableSet(_courses);
    }

    //重构第二步
    public void setCourses(Set arg) {
        Assert.assertTrue(_courses.isEmpty());
        Iterator iter = arg.iterator();
        while (iter.hasNext()) {
            addCourse((Course) iter.next());
        }
//        _courses.addAll(arg);
    }

    public void initializeCourses(Set arg) {
        Assert.assertTrue(_courses.isEmpty());
        Iterator iter = arg.iterator();
        while (iter.hasNext()) {
            addCourse((Course) iter.next());
        }
    }

    /**
     * 重构第一步
     */
    public void addCourse(Course arg) {
        _courses.add(arg);
    }

    public void removeCourse(Course arg) {
        _courses.remove(arg);
    }
}

class Course {
    public Course(String name, boolean isAdvance) {
        System.out.println("course(name,isAdvance)方法。。。");

    }

    public boolean isAdvanced() {
        System.out.println("isAdvanced()方法。。。");
        return true;
    }
}